﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DAL;
using Model;

namespace BLL
{
    public class CategoryBLL
    {
        CategoryDAL dal = new CategoryDAL();
        ProductCategoryDAL productCategoryDAL = new ProductCategoryDAL();
        public List<Category> GetAllCategory()
        {
            return dal.SelectAll();
        }

        public List<TreeNode> GetCategoryTreeNodes()
        {
            List<TreeNode> nodes = new List<TreeNode>();

            var list = dal.SelectAll();
            var root = list.Where(x => x.ParentID == 0).ToList();
            root.ForEach(x =>
            {
                TreeNode node = new TreeNode(x.Name);
                node.Tag = x;
                nodes.Add(node);
                BuildTreeView(node, x, list);
            });
            return nodes;
        }

        protected void BuildTreeView(TreeNode node, Category root, List<Category> list)
        {
            TreeNode childNode = null;
            var data = list.Where(x => x.ParentID == root.ID).ToList();
            data.ForEach(x =>
            {
                childNode = new TreeNode(x.Name);
                childNode.Tag = x;
                node.Nodes.Add(childNode);
                BuildTreeView(childNode, x, list);
            });
        }

        public void Insert(Category category)
        {
            dal.Insert(category);
        }

        public void Update(Category category)
        {
            dal.Update(category);
        }

        public void Delete(long p)
        {
            Category category = new Category { ID = p };
            Delete(category);
        }

        public void Delete(Category category)
        {
            dal.Delete(category);
        }

        public string GetCategoryIDByPID(long pid)
        {
            var list = productCategoryDAL.GetAllByPID(pid);
            var names = from xx in list select xx.CID;
            return string.Join(",", names);
        }

        public List<Category> SeachCategoryByName(string name, List<long> ids = null)
        {
            return dal.SeachCategoryByName(name, ids);
        }
    }
}
